#include "Socket.h"


LPFN_TRANSMITFILE Socket::s_transferFilePointer = NULL;
LPFN_CONNECTEX s_connectEx = NULL;

void wxtl::Socket::startUp( BYTE major /*= 2*/, BYTE minor /*= 0*/, WSADATA *pData /*= NULL*/ ) throw(...)
{
	WSADATA data;

	if (pData == NULL)
		pData = &data;

	if (WSAStartup(MAKEWORD(major, minor), pData) != 0)
		throw _win32_error(WSAGetLastError());	
}

LPFN_TRANSMITFILE tf;

void wxtl::Socket::InitConnectEx()
{
	DWORD returned = 0;
	GUID Guid = WSAID_CONNECTEX;

	int ret = WSAIoctl(m_socket, SIO_GET_EXTENSION_FUNCTION_POINTER, &Guid, sizeof(GUID), &s_connectEx, sizeof(LPFN_CONNECTEX),
		&returned, NULL, NULL);

	if(ret != 0)
	{
		throw _win32_error(WSAGetLastError());
	}
}

bool wxtl::Socket::TransmitFile(File& file, DWORD fileSize, DWORD numberOfBytesPerSend, LPOVERLAPPED overlapped,
	LPTRANSMIT_FILE_BUFFERS transmitBuffers, DWORD flags )
{
	if(s_transferFilePointer == NULL)
	{
		//InitTransimFile();
	}

	//::TransmitFile(m_socket, file.get(), fileSize, numberOfBytesPerSend, overlapped, transmitBuffers, flags);
	//BOOL ret = tf(m_socket, file.get(), fileSize, numberOfBytesPerSend, overlapped, transmitBuffers, flags);
	THROW_BAD_SOCKET_RET(::TransmitFile(m_socket, file.get(), fileSize, numberOfBytesPerSend, overlapped, transmitBuffers, flags));
	

	return true;
}

void wxtl::Socket::connect( UINT port, const CHAR* pSockAddr, LPOVERLAPPED pOverlap ) throw(...)
{
	SockAddrIn addr;
	addr.setC(port, pSockAddr);
	if(!s_connectEx)
	{
		InitConnectEx();
	}

	//DWORD bytes;

	THROW_BAD_SOCKET_RET(s_connectEx(m_socket, addr.ptr(), sizeof(SockAddrIn), NULL, 0, NULL, pOverlap));

	m_remoteAddr = addr;
}

